/**
 * @details: 
 * @brief: 
 * @version: 1.0
 * @author: liuri
 * @Date: 2021-10-05 03:38:40
 * @LastEditors: liuri
 * @LastEditTime: 2021-10-05 05:35:30
 * @FilePath: /TestProject/cPath/vtysh/vector.c
 * @Copyright (C) 2021 liuri. All rights reserved.
 */

#include <stdlib.h>
#include <string.h>
#include "vector.h"



vector vector_init(unsigned int size)
{
    vector v = (vector)calloc(1, sizeof(struct _vector));

    /* allocate at least one slot */
    if (size == 0)
    	size = 1;

    v->alloced = size;
    v->max = 0;
    v->index = calloc(1, sizeof(void *) * size);
    return v;
}

/**
 * @brief: 确保分配的数组大小大于 num
 */
void vector_ensure(vector v, unsigned int num)
{
    if (v->alloced > num)
    	return;

    v->index = realloc(v->index, sizeof (void *) * (v->alloced * 2));
    memset (&v->index[v->alloced], 0, sizeof (void *) * v->alloced);
    v->alloced *= 2;

    if (v->alloced <= num)
    	vector_ensure(v, num);
}

int vector_empty_slot(vector v)
{
    unsigned int i;

    if (v->max == 0)
        return 0;

    for (i = 0; i < v->max; i++)
        if (v->index[i] == 0)
            return i;

    return i;
}

int vector_set_index (vector v, unsigned int i, void *val)
{
    vector_ensure (v, i);

    v->index[i] = val;

    if (v->max <= i)
        v->max = i + 1;

    return i;
}

int vector_set(vector v, void *val)
{
	unsigned int i;

	i = vector_empty_slot (v);
	vector_ensure (v, i);

	v->index[i] = val;

	if (v->max <= i)
		v->max = i + 1;

	return i;
}

void vector_del(vector v, int idx)
{
    if (v->max <= idx)
       return;

    v->index[idx] = 0;    
}


void *vector_get(vector v, unsigned int num)
{
    if (v->alloced < num)
        return NULL;
    if (v->max < num)
        return NULL;

    return v->index[num];
}



void vector_free(vector v)
{
	free(v->index);
	free(v);
}

/**
 * @brief: vector 复制
 */
vector vector_copy(vector v)
{
	unsigned int size;
	vector newv = (vector)calloc(1, sizeof(struct _vector));

	newv->max = v->max;
	newv->alloced = v->alloced;

	size = sizeof(void *) * (v->alloced);
	newv->index = calloc(1, sizeof(void *) * size);
	memcpy (newv->index, v->index, size);

	return newv;
}

/**
 * @brief: 释放容器，不释放index
 */
void vector_wrapper_free(vector v)
{
	free(v);
}

/**
 * @brief: 释放index
 */
void vector_index_free(void *index)
{
	free(index);
}
